import unittest
from time import sleep

import requests
from parameterized import parameterized

from api.reg_login_api import RegLoginApi
from common.util import read_xlsx, read_json, clear_user_info, common_assert


class TestRegLogin(unittest.TestCase):

    def setUp(self) -> None:
        self.session = requests.Session()
        self.reg_login_api = RegLoginApi(self.session)

    def tearDown(self) -> None:
        self.session.close()

    # 获取图片验证码测试用例
    @parameterized.expand(read_json('reg_login_data.json', 'img_verify'))
    def test_img_verify_code(self, r, expected):
        resp = self.reg_login_api.get_img_verify_code(r)

        self.assertEqual(expected, resp.status_code)

    # 获取短信验证码测试用例
    @parameterized.expand(read_json('reg_login_data.json', 'sms_verify'))
    def test_phone_verify_code(self, body, expected):
        clear_user_info(body.get('phone'))

        self.reg_login_api.get_img_verify_code('1')
        resp = self.reg_login_api.get_sms_verify_code(body)
        common_assert(expected, resp)

    # 注册测试用例
    @parameterized.expand(read_json('reg_login_data.json', 'user_reg'))
    def test_register(self, body, expected):
        self.reg_login_api.get_img_verify_code('1')

        req_body = {
            "phone": body.get('phone'),
            "imgVerifyCode": "8888",
            "type": "reg"
        }
        self.reg_login_api.get_sms_verify_code(req_body)
        resp = self.reg_login_api.user_register(body)
        common_assert(expected, resp)

    # 登录测试用例
    @parameterized.expand(read_json('reg_login_data.json', 'user_login'))
    def test_user_login(self, body, expected):
        resp = self.reg_login_api.user_login(body)

        common_assert(expected, resp)

    # 登录测试用例-密码错误校验，在一条用例内执行，不能使用参数化
    def test_user_login_verify(self):
        params_data = read_xlsx('P2P金融项目-接口测试用例.xlsx', '登录注册', 20, 23)

        for i in params_data:
            resp = self.reg_login_api.user_login(i[1])

        sleep(60)
        params_data = read_xlsx('P2P金融项目-接口测试用例.xlsx', '登录注册', 23, 23)
        resp = self.reg_login_api.user_login(params_data[0][1])
        common_assert(params_data[0][2], resp)